from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget, QVBoxLayout, QLineEdit, QLabel
from PySide6.QtCore import Signal
import sys


class MyWindow(QWidget):

    def __init__(self) -> None:
        super().__init__()
        self.subWindow = None
        self.setWindowTitle("MyWindow")
        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText('主窗口文本框')

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.lineEdit)
        self.setLayout(self.mainLayout)
        # 绑定子窗口 & 信号绑定槽
        self.bind()

    def bind(self):
        """
        绑定子窗口和信号的初始化
        :return:
        """
        self.subWindow = SubWindow(self)
        self.subWindow.show()

    def receive(self, text):
        self.lineEdit.setText(text)


class SubWindow(QWidget):
    # DOC: 1. 【定义 Signal】自定义信号（放到init()函数外）
    customSendValToSubWindow = Signal(str)  # 定义信号接收str类型的参数

    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.lb = QLabel('这是子窗口')
        self.lineEdit = QLineEdit()
        # self.lineEdit.setText('子窗口文本框')
        self.lineEdit.setPlaceholderText('子窗口文本框')
        self.button = QPushButton("Press me")
        self.button.clicked.connect(self.sendAndEmit)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.lb)
        self.mainLayout.addWidget(self.lineEdit)
        self.mainLayout.addWidget(self.button)
        self.setLayout(self.mainLayout)
        self.bind()

    def bind(self):
        """
        绑定子窗口和信号的初始化
        :return:
        """
        # DOC: 2. 【绑定 connect】把【信号绑定到槽（接收信号后的处理函数）】
        # self.customSendValToSubWindow.connect(self.parent.lineEdit.setText)
        self.customSendValToSubWindow.connect(self.parent.receive)


    def sendAndEmit(self):
        text = self.lineEdit.text()
        # DOC: 3. 【触发 emit】触发信号
        self.customSendValToSubWindow.emit(text)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.show()

    app.exec()
